<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue';
import { useUserStore } from "@/stores/userStore.js";
import RoleList from '@/components/RoleList/Index.vue';
import { ElMessage } from 'element-plus';

const userStore = useUserStore();
const dialogVisible = ref(false);
const emit = defineEmits(['success']);

// 类型定义
interface User {
  userId: number | null;
  username: string;
  realName: string;
  mobile: string;
  email: string;
  userType: string;
  status: boolean | null;
  roleIds: number[];
}

const user = reactive<User>({
  userId: null,
  username: '',
  realName: '',
  mobile: '',
  email: '',
  userType: '',
  status: null,
  roleIds: [],
});

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  roleIds: [{ required: true, message: '请选择角色', trigger: 'change' }],
};

const userFormRef = ref(null);

// 提交表单
const submitForm = () => {
  userFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const userData = {
          userId: user.userId,
          realName: user.realName,
          mobile: user.mobile,
          email: user.email,
          status: user.status,
          roleIds: user.roleIds,
        };

        await userStore.updateUser(userData);

        // 直接显示成功消息，不依赖于返回结果的判断
        ElMessage.success('更新成功');
        dialogVisible.value = false;
        emit('success', userData); // 触发成功事件，刷新列表
      } catch (error) {
        console.error('更新异常:', error);
        // 检查 error 对象的多种可能属性
        const errorMsg = error?.response?.data?.msg ||
            error?.response?.data?.message ||
            error?.data?.msg ||
            error?.data?.message ||
            error?.message ||
            error?.msg ||
            '未知错误';
        ElMessage.error('更新失败: ' + errorMsg);
      }
    } else {
      ElMessage.warning('请填写完整的表单信息');
    }
  });
};

// 显示对话框
const show = (userInfo: any = {}) => {
  if (userInfo.isDelete === 1) {
    ElMessage.warning('不能编辑已删除的用户');
    return;
  }

  // 更好地处理字段初始化，确保类型正确
  user.userId = userInfo.id || null;
  user.username = userInfo.username || '';
  user.realName = userInfo.realName || '';
  user.mobile = userInfo.mobile || '';
  user.email = userInfo.email || '';
  user.userType = userInfo.userType || '';
  // 确保 status 是布尔值
  user.status = userInfo.status === true || userInfo.status === false ? userInfo.status : null;
  // 确保 roleIds 是数组
  user.roleIds = Array.isArray(userInfo.roleIds) ? userInfo.roleIds : [];

  dialogVisible.value = true;

  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.clearValidate();
    }
  });
};

// 对外暴露方法
defineExpose({
  show,
});
</script>

<template>
  <el-dialog
      title="编辑用户"
      v-model="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
  >
    <el-form :model="user" :rules="rules" ref="userFormRef" label-width="100px">
      <el-form-item label="账号" prop="username">
        <el-input v-model="user.username" placeholder="请输入账号" disabled></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="user.realName" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="user.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="user.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="user.userType" placeholder="请选择用户类型" style="width: 100%;" disabled>
          <el-option label="普通用户" value="USER"></el-option>
          <el-option label="管理员" value="ADMIN"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleIds">
        <RoleList v-model="user.roleIds"></RoleList>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="user.status" placeholder="请选择状态" style="width: 100%;">
          <el-option label="正常" :value="true"></el-option>
          <el-option label="禁用" :value="false"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>
